package com.example.bankseckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.bankseckill.mapper.UserMapper;
import com.example.bankseckill.pojo.SeckillOrder;
import com.example.bankseckill.pojo.User;
import com.example.bankseckill.pojo.vo.*;
import com.example.bankseckill.service.IUserService;
import com.example.bankseckill.utils.CreatNameUtil;
import com.example.bankseckill.utils.CreateAgeByIdentity;
import com.example.bankseckill.utils.JWTUtils;
import com.example.bankseckill.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyangjing
 * @since 2022-01-26
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 登录接口
     * @param user
     * @return
     */
    @Override
    public RespBean login(LoginUser user, HttpServletRequest request) {
        //请求ip
        String ip = request.getRemoteAddr();
        //从ip中取出来
        String  captcha= (String)redisTemplate.opsForValue().get(ip + ":");
        if(captcha==null){
            return RespBean.error(RespBeanEnum.CAPTCHA_ERROR);
        }
        if(StringUtils.isEmpty(user.getCode())||!captcha.equalsIgnoreCase(user.getCode())){
            //验证码为空或者错误
            return RespBean.error(RespBeanEnum.CAPTCHA_ERROR);
        }
        //手机号 密码 为空
        if(null==user||user.getPhone()==null||user.getPassword()==null){
            return RespBean.error(RespBeanEnum.PASSWORD_PHONE_INPUT_ERROR);
        }
        User one = userMapper.selectOne(new QueryWrapper<User>().eq("phone", user.getPhone()));
        if(one==null){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        String Password = MD5Util.formPassToDBpass(user.getPassword(), "1a2b3c4d");
        if(!Password.equals(one.getPassword())){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        if(one.getEnable()==0){
            return RespBean.error("用户处于禁用状态，请联系管理员!");
        }
        Map<String,String> map = new HashMap<>();//用来存放payload
        map.put("id", String.valueOf(one.getId()));
        map.put("name",one.getName());
        map.put("phone",one.getPhone());
        map.put("age", String.valueOf(one.getAge()));
        map.put("email",one.getEmail());
        map.put("username",one.getUsername());
        map.put("avatar",one.getAvatar());
        map.put("admin", String.valueOf(one.getAdmin()));
        String token = JWTUtils.getToken(map);
        return RespBean.success("登录成功！",token);
    }
    /**
     * 注册接口
     * @param registerVo
     * @return
     */
    @Override
    public RespBean register(RegisterVo registerVo) {

        //取出验证码做对比
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String code=(String)valueOperations.get(registerVo.getIdentitycard() + ":" + registerVo.getEmail());
        if(StringUtils.isEmpty(code)||!code.equalsIgnoreCase(registerVo.getVertifycode())){
           return RespBean.error(RespBeanEnum.CAPTCHA_ERROR);
        }
        //防止多次注册
        //身份证
        User indentity= userMapper.selectOne(new QueryWrapper<User>().eq("identitycard", registerVo.getIdentitycard()));
        if(indentity!=null){
            return RespBean.error(RespBeanEnum.REGISTER_IDENTITY_ERROR);
        }
        //手机号
        User phone = userMapper.selectOne(new QueryWrapper<User>().eq("phone", registerVo.getPhone()));
        if(phone!=null){
            return RespBean.error(RespBeanEnum.REGISTER_PHONE_ERROR);
        }
        User user = new User();
        //身份证
        user.setIdentitycard(registerVo.getIdentitycard());
        //姓名
        user.setName(registerVo.getName());
        //电话
        user.setPhone(registerVo.getPhone());
        //年龄
        user.setAge(CreateAgeByIdentity.getPersonAgeFromIdCard(registerVo.getIdentitycard()));
        //邮箱
        user.setEmail(registerVo.getEmail());
        //密码 md5加密
        user.setPassword(MD5Util.formPassToDBpass(registerVo.getPassword(),"1a2b3c4d"));
        //注册时间
        user.setRegisterDate(new Date());
        //上一次登录时间
        user.setLastLoginDate(new Date());
        //设置管理员权限 不是管理员
        user.setAdmin(0);
        // 风险等级
        user.setRiskLevel(0);
        //是否工作
        user.setIsinwork(1);
        //是否失信
        user.setIshonest(0);
        //用户状态
        user.setEnable(1);
        //随机生产用户名
        user.setUsername(CreatNameUtil.getRandomJianHan(5));
        //头像未设置
        int result = userMapper.insert(user);
        if(result!=0){
            return  RespBean.success("注册成功");
        }
        return RespBean.success("注册失败");
    }

    /**
     * 根据token 查询User
     * @param request
     * @param response
     * @param token
     * @return
     */
    @Override
    public User getUserByToken(HttpServletRequest request, HttpServletResponse response, String token) {
        String userId = JWTUtils.getUserId(token);
        if(userId==null){
            return null;
        }
        //用redis做缓存，避免每次请求接口都要重新查询数据库
        User user =(User)redisTemplate.opsForValue().get("user:" + userId);
        if(user==null){
            //从数据里查
            user = userMapper.selectById(userId);
        }
        if(user!=null){
            //消除密码
            user.setPassword(null);
            //放入缓存 设置过期时间
            redisTemplate.opsForValue().set("user:" + userId,user,30, TimeUnit.MINUTES);
        }
        return user;
    }

    /**
     * 管理员登录
     * @param user
     * @param request
     * @return
     */
    @Override
    public RespBean adminlogin(LoginUser user, HttpServletRequest request) {
        //查询验证码
        //请求ip
        String ip = request.getRemoteAddr();
        //从ip中取出来
        String  captcha= (String)redisTemplate.opsForValue().get(ip + ":");
        if(captcha==null){
            return RespBean.error(RespBeanEnum.CAPTCHA_ERROR);
        }
        if(StringUtils.isEmpty(user.getCode())||!captcha.equalsIgnoreCase(user.getCode())){
            //验证码为空或者错误
            return RespBean.error(RespBeanEnum.CAPTCHA_ERROR);
        }
        //手机号 密码 为空
        if(null==user||user.getPhone()==null||user.getPassword()==null){
            return RespBean.error(RespBeanEnum.PASSWORD_PHONE_INPUT_ERROR);
        }
        User one = userMapper.selectOne(new QueryWrapper<User>().eq("phone", user.getPhone()));
        if(one==null){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        if(one.getAdmin()==0){
            return RespBean.error(RespBeanEnum.ADMIN_INVAILD_LOGIN);
        }
        String Password = MD5Util.formPassToDBpass(user.getPassword(), "1a2b3c4d");
        if(!Password.equals(one.getPassword())){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        Map<String,String> map = new HashMap<>();//用来存放payload
        map.put("id", String.valueOf(one.getId()));
        map.put("name",one.getName());
        map.put("phone",one.getPhone());
        map.put("age", String.valueOf(one.getAge()));
        map.put("email",one.getEmail());
        map.put("username",one.getUsername());
        map.put("avatar",one.getAvatar());
        map.put("admin", String.valueOf(one.getAdmin()));
        String token = JWTUtils.getToken(map);
        return RespBean.success(token);
    }

    /**
     * 更新用户头像
     * @param user
     * @param url
     * @return
     */
    @Override
    public RespBean updateUserAvatar(User user, String url) {
        //更新头像
        user.setAvatar(url);
        int result = userMapper.updateById(user);
        if(1==result){
            //更新token
            Map<String,String> map = new HashMap<>();//用来存放payload
            map.put("id", String.valueOf(user.getId()));
            map.put("name",user.getName());
            map.put("phone",user.getPhone());
            map.put("age", String.valueOf(user.getAge()));
            map.put("email",user.getEmail());
            map.put("username",user.getUsername());
            map.put("avatar",user.getAvatar());
            map.put("admin", String.valueOf(user.getAdmin()));
            String token = JWTUtils.getToken(map);
            //更新缓存
            redisTemplate.opsForValue().set("user:" + user.getId(),user,30, TimeUnit.MINUTES);
            return RespBean.success(token);
        }
        return RespBean.error(RespBeanEnum.UPDATE_AVATER_ERROR);
    }

    /**
     * 管理员查看所有用户（分页）
     * @param currentPage
     * @param size
     * @param username
     * @param phone
     * @param identitycard
     * @return
     */
    @Override
    public RespPageBean getAllUserInfo(Integer currentPage, Integer size, String username, String phone, String identitycard) {
        //开启分页
        Page<User> page = new Page<>(currentPage, size);
        //将分页装入mapper层
        IPage<User> userIPage = userMapper.getUserInfoByPage(page,username,phone,identitycard);
        RespPageBean respPageBean = new RespPageBean(200,userIPage.getTotal(), userIPage.getRecords());
        return respPageBean;
    }


}
